library(ggplot2)
library(sf)
library(readxl)
library(dplyr)
library(rnaturalearth)
library(tidyr)

data <- read_excel("Library/CloudStorage/OneDrive-UniversityofGeorgia/Dissertation1/Chapter 1/Rural Systematic Lit Data.xlsx")
glimpse(data)

# Add leading zeros to the count column
data$ISO <- sprintf("%03d", data$ISO)

data$iso_n3 <- data$ISO
data$iso_n3_eh <- data$ISO

data$iso_n3 <- as.character(data$iso_n3)
data$iso_n3_eh <- as.character(data$iso_n3_eh)

# Summarize counts for each ISO
counts <- data %>%
  group_by(ISO) %>%
  summarise(count = n())

data <- left_join(data, counts, by = "ISO")

data <- data %>%
  mutate(count1 = ifelse(count > 25, 25, count))

world_map <- ne_countries(scale = "medium", returnclass = "sf")

glimpse(data)

world_map$iso_n3 <- as.character(world_map$iso_n3)
m_data <- merge(world_map, data, by.x = "iso_n3_eh", by.y = "iso_n3", all.x = TRUE)

m_data1 <- merge(world_map, data, by = "iso_n3", all = TRUE)
m_data1

glimpse(m_data)

str(world_map$iso_n3)
str(data$iso_n3_eh)

# Filter out Antarctica
m_data <- m_data[m_data$iso_a3 != "ATA", ]

glimpse(m_data)

#plots
ggplot() +
  geom_sf(data = m_data, aes(fill = count1), color = "white", lwd = 0.1) +
  scale_fill_viridis_c(name = "Freqency", na.value = "grey90", labels = scales::comma, breaks = c(seq(0, 25, by = 5), Inf)) +
  theme_void() +  # Use theme_void to remove axes and background
  theme(legend.position = "right",
        plot.background = element_rect(color = "black", fill = NA, size = 1))  # Add a black border



library(viridis)

ggplot() +
  geom_sf(data = m_data, aes(fill = count1), color = "white", lwd = 0.1) +
  scale_fill_viridis_c(
    name = "Frequency",
    na.value = "grey90",
    breaks = c(seq(0, 20, by = 5), Inf),
    labels = c(seq(0, 20, by = 5), "25+")
  ) +
  theme_void() +
  theme(
    legend.position = "right",
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5),
    plot.background = element_rect(color = "black", fill = NA, size = 1)
  ) +
  labs(
    title = "World Map with Country Frequencies",
    subtitle = "Data based on ISO Codes"
  )







